#include "purchase.h"
#include "ui_purchase.h"
#include "supplier.h"
#include "inquiresql.h"
#include "inquirepurchasecommodity.h"
#include <QDebug>
#include <QDesktopWidget>
#include <QDateTime>
#include <QMessageBox>
#include <QKeyEvent>
#include <QHeaderView>
//#include <calendar.h>
#include "purchasereceipt.h"
#include "mainwindow.h"

Purchase::Purchase(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Purchase)
{
    ui->setupUi(this);
    this->setLayout(ui->MainLayout);

    //设置自定义的鼠标指针图案
    QCursor *myCursor= new QCursor(QPixmap(":/Mouse/Image/mouse/mouse.png"),15,10);
    setCursor(*myCursor);

    inquireOrderForm = false;
    initStatus = true;

    QStringList headers;
    headers << tr("商品编号") << tr("商品名称") << tr("类别") << tr("规格") << tr("颜色") << tr("品牌")
            << tr("单位") << tr("进货价") << tr("进货数量") << tr("合计");
    ui->tableWidgetPurchase->setColumnCount(10);
    ui->tableWidgetPurchase->setHorizontalHeaderLabels(headers);

    m_purchaseReceipt = new PurchaseReceipt(this);
    m_supplier = new Supplier(this);
    m_purchaseReceipt->hide();
    m_supplier->hide();

    ui->lineEditPurchasePrice->setText("0.00");
    ui->lineEditPurchaseQuantity->setText("0");
    m_currentTableWidgetList.clear();

    QRegExp regExpPrice(" [0-9]{0,6}|[0-9]{0,6}[.]{1}[0-9]{0,2} ");
    QRegExpValidator *pRegExpValidatorPrice = new QRegExpValidator(regExpPrice, this);
    ui->lineEditPurchasePrice->setValidator(pRegExpValidatorPrice);

    QRegExp regExpQuantity("[0-9]{1,6}");
    QRegExpValidator *pRegExpValidatorQuantity = new QRegExpValidator(regExpQuantity, this);
    ui->lineEditPurchaseQuantity->setValidator(pRegExpValidatorQuantity);

    QRegExp regExpCommodityBarcode("[0-9]{1,8}");
    QRegExpValidator *pRegExpValidatorCommodityBarcode = new QRegExpValidator(regExpCommodityBarcode, this);
    ui->lineEditCommodityInformation->setValidator(pRegExpValidatorCommodityBarcode);

    m_inquirePurchaseCommodity = new InquirePurchaseCommodity(this);
    m_inquirePurchaseCommodity->hide();

    QHeaderView* vheaderView = ui->tableWidgetPurchase->verticalHeader();
    vheaderView->setHidden(true);

    //设置每行的大小
    ui->tableWidgetPurchase->setColumnCount(10);
    ui->tableWidgetPurchase->setColumnWidth(0,80);
    ui->tableWidgetPurchase->setColumnWidth(1,190);
    ui->tableWidgetPurchase->setColumnWidth(2,50);
    ui->tableWidgetPurchase->setColumnWidth(3,50);
    ui->tableWidgetPurchase->setColumnWidth(4,50);
    ui->tableWidgetPurchase->setColumnWidth(5,100);
    ui->tableWidgetPurchase->setColumnWidth(6,50);
    ui->tableWidgetPurchase->setColumnWidth(7,90);
    ui->tableWidgetPurchase->setColumnWidth(8,90);
    ui->tableWidgetPurchase->setColumnWidth(9,106);

    //将厂商名称添加到comboBoxSupplier的下拉列表中
    ui->comboBoxSupplier->addItems(m_sql->inquireOwnerName());
    ui->comboBoxSupplier->setCurrentIndex(-1);

    setQtableWidgetHeaderStyle();

    //设置列宽可拖动
//    ui->tableWidgetPurchase->horizontalHeader()->setResizeMode(QHeaderView::Interactive);
//    ui->tableWidgetPurchase->verticalHeader()->setResizeMode(QHeaderView::Interactive);
    //设置table的水平滚动条
    ui->tableWidgetPurchase->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    ui->tableWidgetPurchase->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

    //设置进货单号
    setPurchaseOrderFormNumber();

    connect(m_inquirePurchaseCommodity, SIGNAL(displayCommodityInformation(QString)),
            this, SLOT(slotDisplayCommodityInformation(QString)));
    connect(m_purchaseReceipt, SIGNAL(signalDiaplayPurchaseDetail(QString, PurchaseOrderForm)),
            this, SLOT(slotDisplayPurchaseDetail(QString, PurchaseOrderForm)));
    connect(m_supplier, SIGNAL(updateComboBoxSupplier()),
            this, SLOT(slotUpdateComboBoxSupplier()));

    //添加事件过滤器
    ui->comboBoxSupplier->installEventFilter(this);
    ui->lineEditRemark->installEventFilter(this);
    ui->lineEditCommodityInformation->installEventFilter(this);
    ui->lineEditPurchasePrice->installEventFilter(this);
    ui->lineEditPurchaseQuantity->installEventFilter(this);

    eliminationPushButtonBorder();
    returnInitStatus();
    displayPurchaseCommodityInformation();
}

Purchase::~Purchase()
{
    delete ui;
}

bool Purchase::eventFilter(QObject *target, QEvent *event)
{
    if (       target == ui->comboBoxSupplier || target == ui->lineEditRemark
            || target == ui->lineEditCommodityInformation || target == ui->lineEditPurchasePrice
            || target == ui->lineEditPurchaseQuantity )
    {
        //鼠标左键按下事件
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                if (target == ui->comboBoxSupplier)
                {
                    ui->comboBoxSupplier->setCurrentIndex(-1);
                    return true;
                }
            }
        }

        //鼠标左键释放事件
        if (event->type() == QEvent::MouseButtonRelease)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                if (target == ui->comboBoxSupplier)
                {
                    ui->comboBoxSupplier->showPopup();
                    return true;
                }
            }
        }

        //键盘事件
        if (event->type() == QEvent::KeyPress)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
            if ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))
            {
                if (target == ui->comboBoxSupplier)
                {
                    ui->lineEditRemark->setFocus();
                    ui->lineEditRemark->selectAll();
                    return true;
                }
                if (target == ui->lineEditRemark)
                {
                    ui->lineEditCommodityInformation->setFocus();
                    ui->lineEditCommodityInformation->selectAll();
                    return true;
                }
                if (target == ui->lineEditCommodityInformation)
                {
                    if (!ui->lineEditCommodityInformation->text().isEmpty())
                    {
                        if ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))
                        {
                            if (initStatus)
                                returnPurchaseStatus();
                            HandleLineEditCommodityInformation();
                        }
                        return true;
                    }
                    if (!ui->labelCommodityBarcode->text().isEmpty())
                    {
                        ui->lineEditPurchasePrice->setFocus();
                        ui->lineEditPurchasePrice->selectAll();
                        return true;
                    }
                    return true;
                }
                if (target == ui->lineEditPurchasePrice)
                {
                    ui->lineEditPurchaseQuantity->setFocus();
                    ui->lineEditPurchaseQuantity->selectAll();
                    return true;
                }
                if (target == ui->lineEditPurchaseQuantity)
                {
                    ui->pushButtonAddCommodity->setFocus();
                    if ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))
                        on_pushButtonAddCommodity_clicked();
                    return true;
                }
            }
        }
    }
    return QWidget::eventFilter(target, event);
}

void Purchase::on_pushButtonInquireSupplier_clicked()
{
//    emit displaySupplier();
    m_supplier->displaySupplier();

    m_supplier->setWindowFlags(Qt::Dialog);
    m_supplier->setWindowModality(Qt::ApplicationModal);//在对 QWidget 操作时，不能操作其他东西
    m_supplier->setAttribute(Qt::WA_ShowModal, true);

    m_supplier->move((QApplication::desktop()->width() - m_supplier->width())/2,
               (QApplication::desktop()->height() - m_supplier->height())/2);
    m_supplier->show();

//    slotUpdateComboBoxSupplier();
}

void Purchase::slotUpdateComboBoxSupplier()
{
    ui->comboBoxSupplier->clear();
    ui->comboBoxSupplier->addItems(m_sql->inquireOwnerName());
}

void Purchase::on_pushButtonInquireCommodity_clicked()
{
    if (inquireOrderForm || initStatus)
    {
        returnPurchaseStatus();
    }

//    m_inquirePurchaseCommodity->changelineEditInquire(ui->lineEditCommodityInformation->text());

//    m_inquirePurchaseCommodity->setWindowFlags(
//                Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool );
//    QPoint GlobalPoint(ui->pushButtonInquireCommodity->mapToGlobal(QPoint(0, 0)));
//    int x = GlobalPoint.x();//该控件在窗体中左上角横坐标
//    int y = GlobalPoint.y();//该控件在窗体中左上角纵坐标
////    m_inquirePurchaseCommodity->move(x ,y- 250);
//    m_inquirePurchaseCommodity->setGeometry(x - 250, y - 420, 800, 415);
//    //在对 QWidget 操作时，不能操作其他东西
//    m_inquirePurchaseCommodity->setWindowModality(Qt::ApplicationModal);
//    m_inquirePurchaseCommodity->setAttribute(Qt::WA_ShowModal, true);
//    m_inquirePurchaseCommodity->show();

    m_inquirePurchaseCommodity->changelineEditInquire(
                ui->lineEditCommodityInformation->text());
    m_inquirePurchaseCommodity->setWindowFlags(
                Qt::FramelessWindowHint | Qt::Dialog);
    QPoint GlobalPoint(ui->pushButtonInquireCommodity
                       ->mapToGlobal(QPoint(0, 0)));
    int x = GlobalPoint.x();//该控件在窗体中左上角横坐标
    int y = GlobalPoint.y();//该控件在窗体中左上角纵坐标
    m_inquirePurchaseCommodity->setGeometry(x - 250, y - 440, 800, 425);
    m_inquirePurchaseCommodity->show();

//    m_inquirePurchaseCommodity->changelineEditInquire(
//                ui->lineEditInquireCommodity->text());
//    m_inquirePurchaseCommodity->setWindowFlags(
//                Qt::FramelessWindowHint | Qt::Dialog);
//    QPoint GlobalPoint(ui->pushButtonInquireCommodity
//                       ->mapToGlobal(QPoint(0, 0)));
//    int x = GlobalPoint.x();//该控件在窗体中左上角横坐标
//    int y = GlobalPoint.y();//该控件在窗体中左上角纵坐标
//    m_inquirePurchaseCommodity->setGeometry(x - 250, y - 440, 800, 425);
//    m_inquirePurchaseCommodity->show();
}

void Purchase::slotDisplayCommodityInformation(QString commodityBarcode)
{
    m_list.clear();
    m_list = m_sql->InquireCommodityInformation();

    for(int i = 0; i < m_list.count(); ++i)
    {
        if (commodityBarcode == m_list.at(i).get_commodityBarcode())
        {
            QString specifications = m_sql->InquireAttributeValue(Specification,
                                                                    m_list.at(i).get_specificationsNumber());
            QString category = m_sql->InquireAttributeValue(Category,
                                                                    m_list.at(i).get_categoryNumber());
            QString color = m_sql->InquireAttributeValue(Color, m_list.at(i).get_colorNumber());
            QString brand = m_sql->InquireAttributeValue(Brand, m_list.at(i).get_brandNumbe());
            QString unit = m_sql->InquireAttributeValue(Unit, m_list.at(i).get_unitNumber());

            ui->labelCommodityBarcode->setText(m_list.at(i).get_commodityBarcode());
            ui->labelCommodityName->setText(m_list.at(i).get_commodityName());
            ui->labelCategory->setText(category);
            ui->labelSpecification->setText(specifications);
            ui->labelColor->setText(color);
            ui->labelBrand->setText(brand);
            ui->labelUnit->setText(unit);
            ui->labelStockQuantity->setText(m_list.at(i).get_stockQuantity());
            ui->labelSellingPrice->setText(m_list.at(i).get_sellingPrice());
            ui->labelMemberPrice->setText(m_list.at(i).get_memberPrice());
            ui->lineEditPurchasePrice->setText(completionStringPrice(m_list.at(i).get_cost()));
            ui->lineEditPurchasePrice->setText(completionStringPrice(
                                            QString::number(m_list.at(i).get_cost().toDouble(), 'd', 2)));
            ui->lineEditPurchaseQuantity->setText(QString::number(0));

            ui->lineEditPurchasePrice->setFocus();
            ui->lineEditPurchasePrice->selectAll();
            break;
        }
    }
}

void Purchase::on_pushButtonAddCommodity_clicked()
{
    if (ui->labelCommodityBarcode->text().isEmpty())
    {
        //静态的引用QMessageBox 第一个参数是父窗口的句柄,不能为空
        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("请先选择需要入库的商品信息") );
        ui->lineEditCommodityInformation->setFocus();
        return;
    }

    if (ui->lineEditPurchaseQuantity->text().toInt() == 0)
    {
        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("入库数量不能≤0") );
        ui->lineEditPurchaseQuantity->setFocus();
        ui->lineEditPurchaseQuantity->setText("0");
        ui->lineEditPurchaseQuantity->selectAll();
    }
    else
    {
        for(int i = 0; i < m_currentTableWidgetList.count(); ++i)
        {
            if (ui->labelCommodityBarcode->text()
                    == m_currentTableWidgetList.at(i).get_commodityBarcode())
            {
                switch(QMessageBox::question(this, tr("(☆_☆)温馨提示 ..."),
                                      tr("\n此商品已录入,您是否要再次添加?"),
                                      QMessageBox::No | QMessageBox::Yes ,QMessageBox::Yes))
                {
                    case QMessageBox::Yes:
                    {
                        if (ui->lineEditPurchasePrice->text()
                                != m_currentTableWidgetList.at(i).get_cost())
                        {
                            Commodity commodity;
                            switch(QMessageBox::question(this, tr("(☆_☆)温馨提示 ..."),
                              tr("\n进货价存在差异,您是否以此次输入的为准?"),
                              QMessageBox::No | QMessageBox::Yes, QMessageBox::Yes))
                            {
                                case QMessageBox::Yes:
                                    commodity = m_currentTableWidgetList.at(i);
                                    commodity.set_cost(
                                        QString::number(ui->lineEditPurchasePrice->text().toDouble()));
                                    m_currentTableWidgetList.replace(i, commodity);
                                    break;

                                default:
                                    break;
                            }
                        }
                        int purchaseQuantity = m_currentTableWidgetList.at(i).get_purchaseQuantity().toInt()
                                + ui->lineEditPurchaseQuantity->text().toInt();
                        Commodity commodity = m_currentTableWidgetList.at(i);
                        double total = commodity.get_cost().toDouble()
                                * purchaseQuantity;
                        commodity.set_purchaseQuantity(QString::number(purchaseQuantity));
                        commodity.set_purchaseTotal(QString::number(total));
                        m_currentTableWidgetList.replace(i, commodity);
                        displayPurchaseCommodityInformation();
                        return;
                    }
                    case QMessageBox::No:
                        break;
                    default:
                        break;
                }
                return;
            }
        }

        addPurchaseCommodity();
        displayPurchaseCommodityInformation();
        initBottomInformation();
        ui->lineEditCommodityInformation->setFocus();
    }
}


void Purchase::displayPurchaseCommodityInformation()
{
//    qDebug() << "exec";
    ui->tableWidgetPurchase->clear();
    QStringList headers;
    headers << tr("商品编号") << tr("商品名称") << tr("类别") << tr("规格") << tr("颜色") << tr("品牌")
            << tr("单位") << tr("进货价") << tr("进货数量") << tr("合计");

    ui->tableWidgetPurchase->setColumnCount(10);
    ui->tableWidgetPurchase->setHorizontalHeaderLabels(headers);

    setQtableWidgetHeaderStyle();

    //显示进货商品信息
    ui->tableWidgetPurchase->setRowCount(m_currentTableWidgetList.count());

    for(int i = 0; i < m_currentTableWidgetList.count(); ++i)
    {
        QTableWidgetItem *commodityBarcode      = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_commodityBarcode());
        QTableWidgetItem *commodityName         = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_commodityName());
        QTableWidgetItem *category              = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_categoryNumber());
        QTableWidgetItem *specifications        = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_specificationsNumber());
        QTableWidgetItem *color                 = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_colorNumber());
        QTableWidgetItem *brand                 = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_brandNumbe());
        QTableWidgetItem *unit                  = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_unitNumber());
        QTableWidgetItem *cost                  = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_cost());
        QTableWidgetItem *purchaseQuantity      = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_purchaseQuantity());
        QTableWidgetItem *purchaseTotal         = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_purchaseTotal());

        //设置商品编号,单价 数量 合计 为居中对齐
        commodityBarcode->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        cost->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        purchaseQuantity->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        purchaseTotal->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );

        cost->setTextColor(QColor(255,0,255)); //设置文字颜色
        purchaseQuantity->setTextColor(QColor(255,0,255)); //设置文字颜色
        purchaseTotal->setTextColor(QColor(255,0,255)); //设置文字颜色

        //设置文字字体大小
        commodityBarcode->setFont(QFont("DejaVu Sans", 11, 2, false));
        commodityName->setFont(QFont("DejaVu Sans", 11, 2, false));
        category->setFont(QFont("DejaVu Sans", 11, 2, false));
        specifications->setFont(QFont("DejaVu Sans", 11, 2, false));
        color->setFont(QFont("DejaVu Sans", 11, 2, false));
        brand->setFont(QFont("DejaVu Sans", 11, 2, false));
        unit->setFont(QFont("DejaVu Sans", 11, 2, false));
        cost->setFont(QFont("DejaVu Sans", 11, 2, false));
        purchaseQuantity->setFont(QFont("DejaVu Sans", 11, 2, false));
        purchaseTotal->setFont(QFont("DejaVu Sans", 11, 2, false));

        ui->tableWidgetPurchase->setItem(i, 0, commodityBarcode);
        ui->tableWidgetPurchase->setItem(i, 1, commodityName);
        ui->tableWidgetPurchase->setItem(i, 2, category);
        ui->tableWidgetPurchase->setItem(i, 3, specifications);
        ui->tableWidgetPurchase->setItem(i, 4, color);
        ui->tableWidgetPurchase->setItem(i, 5, brand);
        ui->tableWidgetPurchase->setItem(i, 6, unit);
        ui->tableWidgetPurchase->setItem(i, 7, cost);
        ui->tableWidgetPurchase->setItem(i, 8, purchaseQuantity);
        ui->tableWidgetPurchase->setItem(i, 9, purchaseTotal);
    }

    ui->tableWidgetPurchase->setCurrentItem(
                ui->tableWidgetPurchase->item(m_currentTableWidgetList.count() - 1, 0));

    setTableWidgetColor();
}

void Purchase::completionPrice(QLineEdit *lineEdit)
{
    if (lineEdit->text().isEmpty() || lineEdit->text().toDouble() == 0)
    {
        lineEdit->setText("0.00");
        return;
    }

    if (lineEdit->text().contains(".", Qt::CaseInsensitive))
    {
        if (lineEdit->text().right(1) == ".")
        {
            lineEdit->setText(lineEdit->text() + "00");
            return;
        }
        if (lineEdit->text().right(2).contains(".", Qt::CaseInsensitive))
            lineEdit->setText(lineEdit->text() + "0");
    }
    else
    {
        lineEdit->setText(lineEdit->text() + ".00");
    }
}

QString Purchase::completionStringPrice(const QString &price)
{
    QString number = price;
    if (number.isEmpty())
    {
        number.append("0.00");
        return number;
    }
    if (number.contains(".", Qt::CaseInsensitive))
    {
        if (number.left(1) == ".")
        {
            number.replace(0, 1, "0.");
            return number;
        }
        if (number.right(1) == ".")
        {
            number.append("00");
            return number;
        }
        if (number.right(2).contains(".", Qt::CaseInsensitive))
        {
            number.append("0");
            return number;
        }
//        if (!number.right(3).contains(".", Qt::CaseInsensitive))
//        {
//            //需要四舍五入
//            for (int i = 4; i < number.count(); ++i)
//            {
//                if (number.right(i).contains(".", Qt::CaseInsensitive))
//                {
//                    number.right(i).
//                }
//            }
//        }
    }
    else
    {
        number.append(".00");
        return number;
    }

    return NULL;
}

void Purchase::clearCommodityPurchaseList()
{
    ui->tableWidgetPurchase->clear();
    QStringList headers;
    headers << tr("商品编号") << tr("商品名称") << tr("类别") << tr("规格") << tr("颜色") << tr("品牌")
            << tr("单位") << tr("进货价") << tr("进货数量") << tr("合计");

    ui->tableWidgetPurchase->setColumnCount(10);
    ui->tableWidgetPurchase->setHorizontalHeaderLabels(headers);
    ui->tableWidgetPurchase->setRowCount(0);
    setQtableWidgetHeaderStyle();
}

void Purchase::setTableWidgetColor()
{
    for (int i = 0; i < ui->tableWidgetPurchase->rowCount(); ++i)
    {
        if (i % 2 == 0)
        {
            for (int j = 0; j < ui->tableWidgetPurchase->columnCount(); ++j)
            {
                QTableWidgetItem *item = ui->tableWidgetPurchase->item(i,j);
                if (item)
                {
                    const QColor color = QColor(252, 222, 156);
                    item->setBackgroundColor(color);
                }
//                if (j >= 7)
//                {
//                    const QColor color = QColor(255, 0, 0);
//                    item->setTextColor();
//                }
            }
        }
    }
}

void Purchase::setQtableWidgetHeaderStyle()
{
    for (int i = 0; i < 7; ++i)
    {
        ui->tableWidgetPurchase->horizontalHeaderItem(i)->setFont(QFont("Helvetica", 12, 2, false));
        ui->tableWidgetPurchase->horizontalHeaderItem(i)->setTextColor(QColor(200,111,30));
    }
    for (int i = 7; i < 10; ++i)
    {
        ui->tableWidgetPurchase->horizontalHeaderItem(i)->setFont(QFont("Helvetica", 12, 2, false));
        ui->tableWidgetPurchase->horizontalHeaderItem(i)->setTextColor(QColor(0,0,255));
    }
}

void Purchase::initBottomInformation()
{
    ui->labelCommodityBarcode->setText(NULL);
    ui->labelCommodityName->setText(NULL);
    ui->labelCategory->setText(NULL);
    ui->labelSpecification->setText(NULL);
    ui->labelColor->setText(NULL);
    ui->labelBrand->setText(NULL);
    ui->labelUnit->setText(NULL);
    ui->labelStockQuantity->setText("0");
    ui->labelSellingPrice->setText("0.00");
    ui->labelMemberPrice->setText("0.00");
    ui->lineEditPurchasePrice->setText("0.00");
    ui->lineEditPurchaseQuantity->setText("0");
}

void Purchase::HandleLineEditCommodityInformation()
{
    if (inquireOrderForm)
    {
        returnPurchaseStatus();
    }
    m_list.clear();
    m_list = m_sql->InquireCommodityInformation();

    for(int i = 0; i < m_list.count(); ++i)
    {
        if (ui->lineEditCommodityInformation->text() == m_list.at(i).get_commodityBarcode())
        {
            slotDisplayCommodityInformation(ui->lineEditCommodityInformation->text());
            ui->lineEditPurchasePrice->setFocus();
            ui->lineEditPurchasePrice->selectAll();
            ui->lineEditCommodityInformation->setText(NULL);
            return;
        }
    }

    m_inquirePurchaseCommodity->changelineEditInquire(
                ui->lineEditCommodityInformation->text());
    m_inquirePurchaseCommodity->setWindowFlags(
                Qt::FramelessWindowHint | Qt::Dialog);
    QPoint GlobalPoint(ui->pushButtonInquireCommodity
                       ->mapToGlobal(QPoint(0, 0)));
    int x = GlobalPoint.x();//该控件在窗体中左上角横坐标
    int y = GlobalPoint.y();//该控件在窗体中左上角纵坐标
    m_inquirePurchaseCommodity->setGeometry(x - 250, y - 440, 800, 425);
    m_inquirePurchaseCommodity->show();
}

void Purchase::addPurchaseCommodity()
{
    double total = ui->lineEditPurchasePrice->text().toDouble()
            * ui->lineEditPurchaseQuantity->text().toInt();
    Commodity temp(ui->labelCommodityBarcode->text(), ui->labelCommodityName->text(),
                   ui->labelCategory->text(), ui->labelSpecification->text(),
                        ui->labelColor->text(), ui->labelBrand->text(), ui->labelUnit->text(),
                   ui->lineEditPurchasePrice->text(),
                   QString::number(ui->lineEditPurchaseQuantity->text().toInt()),
                   completionStringPrice(QString::number(total)),
                   ui->LabelPurchaseOrderFormNumber->text());

    m_currentTableWidgetList.append(temp);
}

void Purchase::eliminationPushButtonBorder()
{
    //消除边框
    ui->pushButtonAddCommodity->setFlat(true);
    ui->pushButtonClearCommodityList->setFlat(true);
    ui->pushButtonDeleteCommodity->setFlat(true);
    ui->pushButtonDeleteList->setFlat(true);
    ui->pushButtonInquireCommodity->setFlat(true);
    ui->pushButtonInquireList->setFlat(true);
    ui->pushButtonInquireSupplier->setFlat(true);
    ui->pushButtonNewList->setFlat(true);
    ui->pushButtonSaveList->setFlat(true);
}

//按下新单按钮时初始化到进货状态
void Purchase::returnPurchaseStatus()
{
    initStatus = false;
    ui->pushButtonNewList->setDisabled(true);
    ui->pushButtonSaveList->setDisabled(false);
    ui->pushButtonDeleteList->setDisabled(true);
    ui->pushButtonAddCommodity->setDisabled(false);
    ui->pushButtonDeleteCommodity->setDisabled(false);
    ui->pushButtonClearCommodityList->setDisabled(false);
    ui->tableWidgetPurchase->clear();
    m_currentTableWidgetList.clear();
    ui->tableWidgetPurchase->setRowCount(0);
    initBottomInformation();
    inquireOrderForm = false;
    ui->lineEditCommodityInformation->setFocus();
//    ui->lineEditCommodityInformation->setText(NULL);
    ui->comboBoxSupplier->setCurrentIndex(-1);
    ui->lineEditRemark->setText(NULL);
    setPurchaseOrderFormNumber();
    displayPurchaseCommodityInformation();
}

void Purchase::returnInquireOrderFormStatus()
{
    ui->pushButtonNewList->setDisabled(false);
    ui->pushButtonSaveList->setDisabled(true);
    ui->pushButtonDeleteList->setDisabled(false);
    ui->pushButtonAddCommodity->setDisabled(true);
    ui->pushButtonDeleteCommodity->setDisabled(true);
    ui->pushButtonClearCommodityList->setDisabled(true);
    initBottomInformation();
}

void Purchase::returnInitStatus()
{
    ui->pushButtonNewList->setDisabled(false);
    ui->pushButtonSaveList->setDisabled(true);
    ui->pushButtonDeleteList->setDisabled(true);
    ui->pushButtonAddCommodity->setDisabled(false);
    ui->pushButtonDeleteCommodity->setDisabled(false);
    ui->pushButtonClearCommodityList->setDisabled(false);
    initBottomInformation();
    ui->lineEditRemark->setText(NULL);
    ui->comboBoxSupplier->setCurrentIndex(-1);
    ui->lineEditCommodityInformation->setText(NULL);
    ui->tableWidgetPurchase->clear();
    m_currentTableWidgetList.clear();
    ui->lineEditCommodityInformation->setFocus();
    ui->tableWidgetPurchase->setRowCount(0);
}

void Purchase::setPurchaseOrderFormNumber()
{
    m_purchaseOrderFormlist = m_sql->InquirePurchaseOrderForm("all", "all");
    QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间

    if (m_purchaseOrderFormlist.at(m_purchaseOrderFormlist.count() - 1).get_purchaseDate()
            < time.toString("yyyy-MM-dd"))
    {
        QString str = time.toString("yyyyMMdd"); //设置显示格式
        ui->LabelPurchaseOrderFormNumber->setText("JH"+str+"0001");
    }
    else
    {
        QString str = time.toString("yyyyMMdd"); //设置显示格式
        ui->LabelPurchaseOrderFormNumber->setText("JH"+str+QString::number(m_purchaseOrderFormlist
                                    .at(m_purchaseOrderFormlist.count() - 1)
                                    .get_purchaseOrderFormNumber()
                                    .mid(10, 4).toInt() + 1).rightJustified(4, '0'));
    }
}

void Purchase::on_lineEditPurchasePrice_editingFinished()
{
//    if ()
    completionPrice(ui->lineEditPurchasePrice);
}

void Purchase::on_pushButtonClearCommodityList_clicked()
{
    if (ui->tableWidgetPurchase->rowCount())
    {
        switch(QMessageBox::question(this, tr("     ★温馨提示★"),
                                     tr("您确定要清空当前的进货列表吗"),
                                     QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))
        {
            case QMessageBox::Yes:
                m_currentTableWidgetList.clear();
                clearCommodityPurchaseList();
                initBottomInformation();
                ui->lineEditCommodityInformation->setFocus();
                break;
            case QMessageBox::No:
                break;
            default:
                break;
        }
        return;
    }
    if (!ui->labelCommodityBarcode->text().isEmpty())
    {
        ui->lineEditPurchasePrice->setFocus();
        ui->lineEditPurchasePrice->selectAll();
        return;
    }
    else
    {
        ui->lineEditCommodityInformation->setFocus();
        ui->lineEditCommodityInformation->selectAll();
        return;
    }
}

void Purchase::on_pushButtonDeleteCommodity_clicked()
{
    if (ui->tableWidgetPurchase->currentRow() >= 0)
    {
        for(int i = 0; i < m_currentTableWidgetList.count(); ++i)
        {
            if(m_currentTableWidgetList.at(i).get_commodityBarcode() ==
                    ui->tableWidgetPurchase->item(ui->tableWidgetPurchase->currentRow(), 0)->text())
            {
                m_currentTableWidgetList.removeAt(i);
                displayPurchaseCommodityInformation();
                ui->lineEditCommodityInformation->setFocus();
                ui->lineEditCommodityInformation->selectAll();
                return;
            }
        }
    }
    if (ui->tableWidgetPurchase->rowCount() == 0 &&
            (!ui->labelCommodityBarcode->text().isEmpty()))
    {
        ui->lineEditPurchasePrice->setFocus();
        ui->lineEditPurchasePrice->selectAll();
        return;
    }
    else
    {
        ui->lineEditCommodityInformation->setFocus();
        ui->lineEditCommodityInformation->selectAll();
    }
}

void Purchase::on_pushButtonSaveList_clicked()
{
    if (ui->comboBoxSupplier->currentText().isEmpty())
    {
        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("请先选择供货单位信息") );
        return;
    }
    if (!m_currentTableWidgetList.count())
    {
        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("请录入进货商品") );
        return;
    }
    else
    {
        PurchaseOrderForm purchaseOrderForm(QDateTime::currentDateTime().toString("yyyy-MM-dd"),
                        ui->LabelPurchaseOrderFormNumber->text(), ui->comboBoxSupplier->currentText(),
                        MainWindow::staffID, ui->lineEditRemark->text());
//        qDebug() << MainWindow::staffID;
        if (!m_sql->InsertPurchaseOrderForm(purchaseOrderForm))
        {
            QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("插入进货单据失败") );
            return;
        }
        if (!m_sql->InsertpurchaseDetail(m_currentTableWidgetList))
        {
            QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("插入进货明细失败") );
            return;
        }
        m_purchaseReceipt->displayTableWidgetPurchaseOrderForm();
        returnInitStatus();
        initStatus = true;
    }
}

void Purchase::on_pushButtonInquireList_clicked()
{
    m_purchaseReceipt->move((QApplication::desktop()->width() - m_purchaseReceipt->width())/2,
                     (QApplication::desktop()->height() - m_purchaseReceipt->height())/2);
    m_purchaseReceipt->setWindowFlags(Qt::Dialog);
    m_purchaseReceipt->initLineEditTime();
    //在对 QWidget 操作时，不能操作其他东西
    m_purchaseReceipt->setWindowModality(Qt::ApplicationModal);
    m_purchaseReceipt->setAttribute(Qt::WA_ShowModal, true);
    m_purchaseReceipt->displayTableWidgetPurchaseOrderForm();
    m_purchaseReceipt->show();
}

void Purchase::slotDisplayPurchaseDetail(QString purchaseOrderFormNumber,
                                         PurchaseOrderForm purchaseOrderForm)
{
    returnInquireOrderFormStatus();

    inquireOrderForm = true;
    initStatus = false;
    m_currentTableWidgetList.clear();
    m_currentTableWidgetList = m_sql->InquirePurchaseDetail(purchaseOrderFormNumber);
    displayPurchaseCommodityInformation();

    //显示订单中的供货商
    for (int i = 0; i < ui->comboBoxSupplier->count(); ++i)
    {
        if (ui->comboBoxSupplier->itemText(i) == purchaseOrderForm.get_supplier())
        {
            ui->comboBoxSupplier->setCurrentIndex(i);
            break;
        }
    }
    //显示订单中的订单号 备注
    ui->LabelPurchaseOrderFormNumber->setText(purchaseOrderForm.get_purchaseOrderFormNumber());
    ui->lineEditRemark->setText(purchaseOrderForm.get_remark());

//    ui->pushButtonAddCommodity->setDisabled(true);
//    ui->pushButtonDeleteCommodity->setDisabled(true);
//    ui->pushButtonClearCommodityList->setDisabled(true);
}

void Purchase::on_pushButtonNewList_clicked()
{
    initStatus = false;
    returnPurchaseStatus();
}

void Purchase::on_pushButtonDeleteList_clicked()
{
    switch(QMessageBox::question(this, tr("(☆_☆)温馨提示 ..."),
                          tr("您确定要删除单号为 : %1 的进货记录吗?"
                             "\n删除进货记录后, 将撤销此次库存进货数量")
                                 .arg(ui->LabelPurchaseOrderFormNumber->text()),
                          QMessageBox::No | QMessageBox::Yes ,QMessageBox::Yes))
    {
        case QMessageBox::Yes:
            m_sql->DeletePurchaseOrderForm(m_currentTableWidgetList);
            returnInitStatus();
            break;
        case QMessageBox::No:
            break;
        default:
            break;
    }
}
